import qs from 'qs'
import axios from 'axios'
import Vue from 'vue'

export const http = axios.create({
    timeout: 20000,
    headers: {'X-Requested-With': 'XMLHttpRequest'},
    withCredentials: true,
    transformRequest: [data => qs.stringify(data)],  // for POST, PUT, PATCH requests
    paramsSerializer: qs.stringify                   // for GET request
})
export const contextPah = ""
http.interceptors.request.use(function (config) {
    config.url = contextPah + config.url;
    return config
})

export function resource(path, http, actions) {
    let defaultActions = {
        get: id => http.get(path + "/" + id),
        del: id => http.delete(path + "/" + id),
        deleteBatch: idArray => http.delete(path, {
            params: {
                items: idArray
            }
        }),
        add: obj => jsonRequest(path, "post", obj),
        modify: obj => jsonRequest(path, "put", obj),
        save: (obj, method) => {
            if (method !== "post" && method !== 'put') {
                throw new Error('保存只能够为post或get');
            }
            return jsonRequest(path, method, obj)
        },
        list: params => http.get(path + "/list", {params}),
        exists: (rule, value) => {
            let params = {}
            params[rule.field] = value
            return http.get(path + "/validation", {params})
        },
        paging: (options) => pageRequest(options, path),
        http
    }

    return Object.assign(defaultActions, actions)
}

export const jsonRequest = function (path, method, data) {
    return http[method](path, data, {
        headers: {'Content-Type': 'application/json'},
        transformRequest: [data => JSON.stringify(data)]
    })
}

export const pageRequest = (state, path) => {
    state.loading = true
    if (state.table.pageSize) {
        state.queryParams.rows = state.table.pageSize
    }
    if (state.table.pageNumber) {
        state.queryParams.page = state.table.pageNumber
    }
    return new Promise((resolve, reject) => {
        http.get(path, {params: state.queryParams}).then(async res => {
            state.table.rows = res.data.rows
            state.table.total = res.data.total
            state.table.pageSize = res.data.pageSize
            state.table.pageNumber = res.data.pageNumber
            resolve(res)
            await Vue.nextTick()
            state.loading = false
        }).catch(reject)
    })
}



export const User = resource('/user', http, {})